package com.tledu.zyf.manager;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.tledu.zyf.model.IPAndLocationPojo;
import com.tledu.zyf.util.FileOperatorUtil;
import com.tledu.zyf.util.IPUtil;
import com.tledu.zyf.util.RegexUtil;
import com.tledu.zyf.util.SerDeUtil;
import com.tledu.zyf.util.StaticValue;

public class DataProcessManager {

	// 排序之后的数组
	public static IPAndLocationPojo[] ipAndLocationPojoArray;
	static {
		// 判断是否序列化
		boolean isInitFlag = new File(StaticValue.serde_obj_filepath).exists();
		if (isInitFlag) {
			// 到这里说明序列化过,直接读取
			try {
				Object obj = SerDeUtil.getObj(StaticValue.serde_obj_filepath,
						StaticValue.cacheByteArrayLength);

				ipAndLocationPojoArray = (IPAndLocationPojo[]) obj;
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	// else {
	// // 到这里说明没有序列化
	// try {
	// // 结构化
	// List<IPAndLocationPojo> ipAndLocationPojos = DataProcessManager
	// .getPojoList(StaticValue.filePath, StaticValue.charset);
	// // 排序并转换为 数组
	// ipAndLocationPojoArray = DataProcessManager
	// .convertListToArrayAndSort(ipAndLocationPojos);
	//
	// // 序列化
	// SerDeUtil.saveObj(ipAndLocationPojoArray,
	// StaticValue.serde_obj_filepath,
	// StaticValue.cacheByteArrayLength);
	//
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	public static IPAndLocationPojo[] convertListToArrayAndSort(
			List<IPAndLocationPojo> ipAndLocationPojos) {
		// 创建数组
		IPAndLocationPojo[] ipAndLocationPojoArray = new IPAndLocationPojo[ipAndLocationPojos
				.size()];
		// 转换为数组
		ipAndLocationPojos.toArray(ipAndLocationPojoArray);
		// 排序
		Arrays.sort(ipAndLocationPojoArray);
		return ipAndLocationPojoArray;
	}

	/**
	 * 把List<String> 结构化,返回 List<IPAndLocationPojo>
	 * 
	 * @param filePath
	 *            IP地址库文件地址
	 * @param charset
	 *            字符编码
	 * @return
	 */
	public static List<IPAndLocationPojo> getPojoList(String filePath,
			String charset) throws IOException {

		List<String> lineList = FileOperatorUtil.getLineList(filePath, charset);

		// 封装对象的集合
		List<IPAndLocationPojo> ipAndLocationPojos = new ArrayList<IPAndLocationPojo>();
		for (String line : lineList) {
			// 处理空行
			if (line == null || line.trim().equals("")) {
				continue;
			}
			// 以制表符分割,得到字符串数组
			String[] columnArray = line.split("\t");
			// 获取起始IP
			String startIP = columnArray[0];
			// 获取结束IP
			String endIP = columnArray[1];
			// 获取归属地
			String location = columnArray[2];

			// 封装成对象
			IPAndLocationPojo ipAndLocationPojo = new IPAndLocationPojo(
					startIP, endIP, location);
			// 把对象封装到集合中
			ipAndLocationPojos.add(ipAndLocationPojo);
		}

		return ipAndLocationPojos;
	}

	/**
	 * 二分法实现,入参是数组和IP地址
	 * 
	 * @param ipAndLocationPojoArray
	 * @param aidIP
	 * @param startIndex
	 * @param endIndex
	 * @return
	 */
	public static int binaraySearchIPAndLocationPojo(
			IPAndLocationPojo[] ipAndLocationPojoArray, String aidIP,
			int startIndex, int endIndex) {
		// 起始大于结束 终止
		if (startIndex > endIndex) {
			return -1;
		}

		// 中间值
		int middle = (startIndex + endIndex) / 2;

		long ipLong = IPUtil.ipToLong(aidIP);
		if (ipLong > ipAndLocationPojoArray[middle].getEndIPLong()) {
			startIndex = middle + 1;
		} else if (ipLong < ipAndLocationPojoArray[middle].getStartIPLong()) {
			endIndex = middle - 1;
		} else {
			return middle;
		}
		// 递归调用
		return binaraySearchIPAndLocationPojo(ipAndLocationPojoArray, aidIP,
				startIndex, endIndex);
	}

	/**
	 * 对外提供的接口
	 * 
	 * 入参是IP 出参是归属地
	 */
	public static String getLocation(String ip) {

		// IP校验
		if (!RegexUtil.isValidIP(ip)) {
			return "你丫地址输错了!";
		}

		// 二分法
		int startIndex = 0;
		int endIndex = ipAndLocationPojoArray.length - 1;
		int resultIndex = DataProcessManager.binaraySearchIPAndLocationPojo(
				ipAndLocationPojoArray, ip, startIndex, endIndex);

		// 校验结果
		if (resultIndex == -1) {
			return null;
		}
		// 返回归属地
		return ipAndLocationPojoArray[resultIndex].getLocation();
	}
}
